package com.hdwx.weike.dao;

import com.hdwx.weike.Utils.JdbcUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * Created by hdwx on 2017/1/5.
 */
public class HotSearchDao extends BaseDao{
    //通过名字查询搜索次数
    public int queryCountByName(String searchName){
        String table="t_hot_search";
        String[] col={"search_count"};
        String condition="search_name='"+searchName+"'";
        ResultSet set=null;
        try {
            set = query(table, col, condition, null);
            if(set.next()){
                int count=set.getInt("search_count");
                return count;
            }
        } catch (SQLException e) {

        }finally {
            JdbcUtils.close(set);
        }
        return -1;
    }


    //添加新的搜索关键字
    public boolean addSearchKey(String name){
        String table="t_hot_search";
        String[] col={"search_name","search_count"};
        Object[] value={name,1};
        return insert(table, col, value);
    }
    //通过名字更新搜索次数
    public boolean update(String name,int count){
        String table="t_hot_search";
        String[] col={"search_count"};
        Object[] value={count};
        String condition="search_name='"+name+"'";
        return change(table,col,value,condition);
    }

    //处理用户搜索的关键字，若没有则添加，若有则次数+1
    public boolean dealSearchKey(String name){
        int i = queryCountByName(name);
        if(i!=-1){//数据库中有该关键字，更新次数
            i=i+1;
            return update(name, i);
        }else{//数据库中没有关键字，添加
            return addSearchKey(name);
        }
    }

    //按搜索次数排序查询搜索关键字
    public List<String> queryHotKey(){
        List<String> list=new ArrayList<String>();//创建一个集合装查询到的热门关键字
        String table="t_hot_search order by search_count desc";
        String[] col={"search_name"};
        int[] limit={0,20};
        ResultSet set=null;
        try {
           set = query(table,col,null,limit);
            while (set.next()){
                list.add(set.getString("search_name"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.close(set);
        }
        return list;
    }

//    public static void main(String[] args) {
//        boolean hh = new HotSearchDao().dealSearchKey("11");
//        System.out.println(hh);
//    }
}
